package org.lynn.lambda.test;

import org.junit.Test;
import org.lynn.lambda.function.ConsumerInterface;

import java.util.*;

/**
 * lambda表达式和匿名类
 *
 * @author linzou@linkdoc.com
 * @ClassName: LambdaExpressionAndAnonymousClasses
 * @Description:
 * @date 2019/6/4 2:54 PM
 */
public class LambdaExpressionAndAnonymousClasses {


    /**
     * lambda 取代某些匿名内部类
     * 无参函数的简写
     */
    @Test
    public void anonymousClasses() {

        //before java 8
        new Thread(new Runnable() {
            public void run() {
                System.out.println("too match code before java 8");
            }
        }).start();


        //java 8 lambda
        //lambda 表达式的语法
        //(params) -> expression
        //(params) -> statement
        //(params) -> { statements }
        new Thread(() -> System.out.println("lambda is better")).start();

    }

    /**
     * lambda 取代某些匿名内部类
     * 带参数的简写
     */
    @Test
    public void anonymousClassesWithArgs() {

        List<String> list = Arrays.asList("I", "love", "you", "two");

        //jdk7 匿名内部类
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {

                if (Objects.isNull(s1)) {
                    return -1;
                }

                if (Objects.isNull(s2)) {
                    return 1;
                }
                return s1.length() - s2.length();
            }
        });

        //jdk8 lambda表达式
        Collections.sort(list, (s1, s2) -> {

            if (Objects.isNull(s1)) {
                return -1;
            }

            if (Objects.isNull(s2)) {
                return 1;
            }
            return s1.length() - s2.length();

        });

    }


    @Test
    public void functionInterface(){
        ConsumerInterface<String> consumer = str -> System.out.println(str);
    }





}
